package com.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.xutils.DbManager;
import org.xutils.x;
import org.xutils.DbManager.DaoConfig;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class TTUtils {

	
	public static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * toast信息
	 * @param context
	 * @param message
	 */
	public static void toast(Context context,String message){
		Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}
	/** 
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
     */  
    public static int dip2px(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
  
    /** 
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
     */  
    public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
  
    /**
     * 获得bitmap
     * @param path
     * @param width
     * @param height
     * @return
     */
	public static Bitmap getBitmap(String path, int width, int height){
		Bitmap bitmap = null;
		try {
			
			if(bitmap == null){
				try {	
					bitmap = getBitmapFromFile(new File(path), width, height);
					
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	
	/**
	 * 获得图片对象
	 * @param dst
	 * @param width
	 * @param height
	 * @return
	 */
	private static Bitmap getBitmapFromFile(File dst, int width, int height) {  
	    if (null != dst && dst.exists()) {  
	        BitmapFactory.Options opts = null;  
	        if (width > 0 && height > 0) {  
	            opts = new BitmapFactory.Options();  
	            opts.inJustDecodeBounds = true;  
	            BitmapFactory.decodeFile(dst.getPath(), opts);  
	            // 计算图片缩放比例  
	            final int minSideLength = Math.min(width, height);  
	            opts.inSampleSize = computeSampleSize(opts, minSideLength,  width * height);  
	            opts.inJustDecodeBounds = false;  
	            opts.inInputShareable = true;  
	            opts.inPurgeable = true;  
	        }  
	        try {  
	            return BitmapFactory.decodeStream(new FileInputStream(dst.getPath()), null, opts).copy(Bitmap.Config.ARGB_8888, true);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    }  
	    return null;  
	}  
	/**
	 * 限制缩放比例  
	 * @param options
	 * @param minSideLength
	 * @param maxNumOfPixels
	 * @return
	 */
	private static int computeSampleSize(BitmapFactory.Options options,  
	        int minSideLength, int maxNumOfPixels) {  
	    int initialSize = computeInitialSampleSize(options, minSideLength,  
	            maxNumOfPixels);  
	  
	    int roundedSize;  
	    if (initialSize <= 8) {  
	        roundedSize = 1;  
	        while (roundedSize < initialSize) {  
	            roundedSize <<= 1;  
	        }  
	    } else {  
	        roundedSize = (initialSize + 7) / 8 * 8;  
	    }  
	  
	    return roundedSize;  
	}  
	/**
	 * 获得缩放比例  
	 * @param options
	 * @param minSideLength
	 * @param maxNumOfPixels
	 * @return
	 */
	private static int computeInitialSampleSize(BitmapFactory.Options options,  
	        int minSideLength, int maxNumOfPixels) {  
	    double w = options.outWidth;  
	    double h = options.outHeight;  
	  
	    int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math  
	            .sqrt(w * h / maxNumOfPixels));  
	    int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math  
	            .floor(w / minSideLength), Math.floor(h / minSideLength));  
	  
	    if (upperBound < lowerBound) {  
	        // return the larger one when there is no overlapping zone.  
	        return lowerBound;  
	    }  
	  
	    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
	        return 1;  
	    } else if (minSideLength == -1) {  
	        return lowerBound;  
	    } else {  
	        return upperBound;  
	    }  
	}  
	/**
	 * 获取相册图片地址
	 * @param context
	 * @param originalUri
	 * @return
	 */
	public static String getImageUrl(Context context, Uri originalUri) {
        String result = "";
        ContentResolver resolver = context.getContentResolver();
//        Bitmap bm = null;
        try {
//            bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
            String[] proj = {MediaStore.Images.Media.DATA};
//            Cursor cursor = managedQuery(originalUri, proj, null, null, null);
            Cursor cursor = resolver.query(originalUri, proj, null, null, null);
//            Cursor cursor = new CursorLoader(this, originalUri, proj, null, null, null).loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            //最后根据索引值获取图片路径
            result = cursor.getString(column_index);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
	/**
	 * 压缩保存图片
	 * @param path
	 * @param width
	 * @param height
	 * @param isDelete
	 * @return
	 */
	public static String saveImage(String path, int width, int height,boolean isDelete,String markText,Context context){
		FileOutputStream out = null;
		try {
			Bitmap bitmap = getBitmap(path, width, height);
			
			int rota = readPictureDegree(path);
			
			bitmap = rotaingImageView(rota, bitmap);
		
			int bitmapWidth = bitmap.getWidth();
			int bitmapHeight = bitmap.getHeight();
			Canvas canvas = new Canvas(bitmap);// 初始化画布 绘制的图像到icon上

	
			
			int screenWidth = Comm.pWidth;
			float textSize = dip2px(context, 16) * bitmapWidth / screenWidth;
			// 创建画笔
			TextPaint mPaint = new TextPaint();
			// 文字矩阵区域
			Rect textBounds = new Rect();
			// 水印的字体大小
			mPaint.setTextSize(textSize);
			// 文字阴影
			//mPaint.setShadowLayer(0.5f, 0f, 1f, Color.YELLOW);
			// 抗锯齿
			mPaint.setAntiAlias(true);
			// 水印的区域
			mPaint.getTextBounds(markText, 0, markText.length(), textBounds);
			// 水印的颜色
			mPaint.setColor(Color.RED);
			StaticLayout layout = new StaticLayout(markText, 0, markText.length(), mPaint, (int) (bitmapWidth - textSize),
			Alignment.ALIGN_NORMAL, 1.0F, 0.5F, true);
			// 文字开始的坐标
			float textX = dip2px(context, 8) * bitmapWidth / screenWidth;
			float textY = 5;//图片的中间
			// 画文字
			canvas.translate(textX, textY);
			layout.draw(canvas);
			
			
			File vFile = new File(Environment.getExternalStorageDirectory()
					+ "/work/image/", String.valueOf(System.currentTimeMillis())
					+ ".png");
			
			if (!vFile.exists())
			{
				File vDirPath = vFile.getParentFile();
				vDirPath.mkdirs();

			}
			out = new FileOutputStream(vFile);
			bitmap.compress(CompressFormat.PNG, 100, out);
			out.close();
			
			if (isDelete) {
				File file = new File(path);
				file.delete();
			}
			
			path = vFile.getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return path;
	}
	/**
	 * 播打电话
	 * @param context
	 * @param phone
	 */
	public static void makePhone(Context context,String phone){
		Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+phone)); 
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent); 
	}
	
	
	/**
	 * 获取版本号
	 * @return 当前应用的版本号
	 */
	public static int getVersion(Context context) {
	    try {
	        PackageManager manager = context.getPackageManager();
	        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
	        int version = info.versionCode;
	        return  version;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return 0;
	    }
	}
	
	  /**
     * 设置listView高度
     * @param listView
     */
    public static  void setListViewHeightBasedOnChildren(ListView listView) {
		try {
			ListAdapter listAdapter = listView.getAdapter();
			if (listAdapter == null) {
			// pre-condition
			return;
			}
			int totalHeight = 0;
			for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			// listItem.measure(0, 0);
			listItem.measure(
			MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
			MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
			totalHeight += listItem.getMeasuredHeight();
			}
			ViewGroup.LayoutParams params = listView.getLayoutParams();
			params.height = totalHeight
			+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
			listView.setLayoutParams(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		}
    /**
     * MD5加密
     * @param plainText
     * @return
     */
    public static String MD5(String plainText) {
		String re_md5 = new String();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			re_md5 = buf.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return re_md5;
	}
    
    
	
	/**
	 * 判断是否有sd卡
	 * @return
	 */
	public boolean havaSDCard(){
		boolean flag = false;
		try {
			if (Environment.getExternalStorageState().equals(  
				    android.os.Environment.MEDIA_MOUNTED)){
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 判断是否可存储图片（剩余内存最少8MB）
	 * @return
	 */
	public boolean canSave(){
		boolean flag = false;
		try {		
			 File path = Environment.getExternalStorageDirectory();   
		     StatFs sf = new StatFs(path.getPath());   
		     //获取单个数据块的大小(Byte)  
		     long blockSize = sf.getBlockSize();   
		     //空闲的数据块的数量  
		     long freeBlocks = sf.getAvailableBlocks(); 
		     
		     long mb = (freeBlocks * blockSize)/1024/1024;
		     if(mb > 8){
		    	 flag = true;
		     }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 打开图片
	 * @param param
	 * @return
	 */
    public static Intent getImageFileIntent( String param ) {  
        Intent intent = new Intent("android.intent.action.VIEW");  
        intent.addCategory("android.intent.category.DEFAULT");  
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
        Uri uri = Uri.fromFile(new File(param ));  
        intent.setDataAndType(uri, "image/*");  
        return intent;  
    } 
    
    /**
     * android获取一个用于打开音频文件的intent  
     * @param param
     * @return
     */
    public static Intent getAudioFileIntent( String param ) {  
        Intent intent = new Intent("android.intent.action.VIEW");  
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
        intent.putExtra("oneshot", 0);  
        intent.putExtra("configchange", 0);  
        Uri uri = Uri.fromFile(new File(param ));  
        intent.setDataAndType(uri, "audio/*");  
        return intent;  
    }  
    
      
    /**
     * base64字符串转化成图片  
     * @param imgStr
     * @param imgFilePath
     * @return
     */
    public static boolean getBase64ToImage(String imgStr,String imgFilePath)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return false;  
      //  BASE64Decoder decoder = new BASE64Decoder();  
        try   
        {  
//        	StringBuffer sb = new StringBuffer(imgStr);
//        	int m = 0;
//        	
//    		while ((m = sb.indexOf("\\/",m)) > 0) {
//    			System.out.println("m==" + m);
//    			sb.replace(m, m +1, "/");
//    			 System.out.println(sb.toString());
//    		}
        	imgStr = imgStr.replaceAll("\\\\", "");   
        	Log.e("imgStr", "" + imgStr);
        	
            //Base64解码  
            byte[] b = Base64.decode(imgStr, Base64.DEFAULT);
//            for(int i=0;i<b.length;++i)  
//            {  
//                if(b[i]<0)  
//                {//调整异常数据  
//                    b[i]+=256;  
//                }  
//            }  
            //生成jpeg图片  
            
            File file = new File(imgFilePath);
            if (!file.exists()) {
				file.createNewFile();
			}else{
				return true;
			}
            
            OutputStream out = new FileOutputStream(file);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            return false;  
        }  
    }  
    
    
    /**
     * base64字符串转化成图片
     * @param picStrInMsg
     * @param imgFilePath
     * @return
     */
    public static Bitmap getBase64ToImage2(String picStrInMsg,String imgFilePath)  
    {   //对字节数组字符串进行Base64解码并生成图片  
    	
    		Bitmap bitmap = null;

    		byte[] imgByte = null;
    		InputStream input = null;
    		try{
    		imgByte = Base64.decode(picStrInMsg, Base64.DEFAULT);
    		       BitmapFactory.Options options=new BitmapFactory.Options();
    		       options.inSampleSize = 8;
    		       input = new ByteArrayInputStream(imgByte);
    		       SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(input, null, options));
    		       bitmap = (Bitmap)softRef.get();;
    		}catch(Exception e){
    		e.printStackTrace();
    		}finally{
    		if(imgByte!=null){
    		imgByte = null;
    		}

    		if(input!=null){
    		try {
    		input.close();
    		} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    		}
    		}}
    		return bitmap;
    
    }  
    /**
     * 获取当前余额第一天
     * @return
     */
    public static String getFirstDayOfMonth(){
    	//获取当前月第一天：
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
        Calendar c = Calendar.getInstance();    
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
        String first = format.format(c.getTime());
        
        return first + " 00:00:00";
    }
    /**
     * 获取当前余额第一天
     * @return
     */
    public static String getLastDayOfMonth(){
    	  //获取当前月第一天：
    	 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
    	 Calendar ca = Calendar.getInstance();    
         ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));  
         String last = format.format(ca.getTime());
        
        return last + " 23:59:59";
    }
    
    /**
     * 递归方式 计算文件的大小 
     * @param file
     * @return
     */
    public static long getTotalSizeOfFilesInDir(final File file) {
    	try {
    		if (file.isFile())
                return file.length();
            final File[] children = file.listFiles();
            long total = 0;
            if (children != null)
                for (final File child : children)
                    total += getTotalSizeOfFilesInDir(child);
            return total;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return 0;
        
    }
    /**
     * 删除目录
     * @param dir
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    
    /**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
                ExifInterface exifInterface = new ExifInterface(path);
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
        } catch (IOException e) {
                e.printStackTrace();
        }
        return degree;
    }
   /**
    * 旋转图片 
    * @param angle 
    * @param bitmap 
    * @return Bitmap 
    */  
   public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {  
       //旋转图片 动作   
       Matrix matrix = new Matrix();;  
       matrix.postRotate(angle);  
       System.out.println("angle2=" + angle);  
       // 创建新的图片   
       Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  
               bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
       return resizedBitmap;  
   }
   
   /**开启数据库
	 * 
	 * @return
	 */
	public static DbManager getDbManager(){
		
		try {
			DaoConfig daoConfig = new DaoConfig();
			daoConfig.setDbName(Const.DB_NAME);
			daoConfig.setDbVersion(Const.DB_VERSION);
			return x.getDb(daoConfig);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
}
